package com.wuzf.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.wuzf.utils.PageData;

public class BaseController {
	
	protected Logger logger = Logger.getLogger(this.getClass());
	
	private static final long serialVersionUID = 6357869213649815390L;
	
	
	/**
	 * 得到PageData
	 */
	public PageData getPageData(){
		return new PageData(this.getRequest());
	}
	
	/**
	 * 得到ModelAndView
	 */
	public ModelAndView getModelAndView(){
		return new ModelAndView();
	}
	
	/**
	 * 得到request对象
	 */
	public HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		
		return request;
	}
	
	public void login(String configFile, String username, String password) {
		//获取SecurityManager工厂，使用配置文件初始化SecurityManager
		Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory(configFile);
		
		//得到SecurityManager实例，并绑定给SecurityUtils
		org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
		
		SecurityUtils.setSecurityManager(securityManager);
		//得到subject及创建用户名/密码身份验证token
		Subject subject = SecurityUtils.getSubject();
		
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		
		subject.login(token);
	}
	
	public Subject subject() {
		return SecurityUtils.getSubject();
	}
	
	
	/** 
     * 使用@ExceptionHandler注解，继承此类的Controller发生异常时会自动执行该方法 
     * @param request 
     * @param e 
     * @return 
     */  
    @ExceptionHandler  
    public String exception(HttpServletRequest request, Exception e) {  
        //对异常进行判断做相应的处理  
        if(e instanceof UnknownAccountException){  
            return "jsp/accountError";  
        }else{  
            return "error";  
        }  
    } 
}
